package dao;

import java.sql.*;
import java.util.List;

import jdbc.JdbcUtill;

import com.sun.corba.se.spi.ior.MakeImmutable;
import com.sun.org.apache.regexp.internal.recompile;

import model.Message;

public abstract class MessageDao {

	
	public abstract int insert(Connection conn, Message message) throws SQLException;
	
	public Message select(Connection conn, int messageID) throws SQLException {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try{
			pstmt = conn.prepareStatement("select * from guestbook_message where message_id = ?");
			pstmt.setInt(1, messageID);
			rs = pstmt.executeQuery();
			if(rs.next()) {
				return makeMessageFromResultSet(rs);
			} else { 
				return null;
			}
		} finally {
			JdbcUtill.close(rs);
			JdbcUtill.close(pstmt);
		}
		
				
	}
	
	protected Message makeMessageFromResultSet(ResultSet rs) throws SQLException {
		Message message = new Message();
		message.setId(rs.getInt("message_id"));
		message.setGuestName(rs.getString("guest_name"));
		message.setPassword(rs.getString("password"));
		message.setMessage(rs.getString("message"));
		return message;
		
	}
	
	public int selectCount(Connection conn) throws SQLException {
		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select count(*) from guestbook_message");
			rs.next();
			return rs.getInt(1);
		}finally {
			JdbcUtill.close(rs);
			JdbcUtill.close(stmt);
		}
	}
	
	public abstract List<Message> selectList(Connection conn, int firstRow, int endRow) throws SQLException ; 
	
	public int delect(Connection conn, int messageId) throws SQLException {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = conn.prepareStatement("delect from guestbook_message where message_id =? ");
			pstmt.setInt(1, messageId);
			return pstmt.executeUpdate();
		} finally {
			JdbcUtill.close(rs);
			JdbcUtill.close(pstmt);
		}
	}
}